package com.geralt.im.server;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.geralt.im.controller.Controller;
import com.geralt.im.protocol.Request;
import com.geralt.im.protocol.Response;

public class ObjectClientSession extends ClientSession implements Runnable {

	private InputStream is = null;
	private ObjectInputStream ois = null;
	private OutputStream os = null;
	private ObjectOutputStream oos = null;

	public ObjectClientSession(Socket socket) {
		super(socket);

		try {
			is = socket.getInputStream();
			ois = new ObjectInputStream(is);
			os = socket.getOutputStream();
			oos = new ObjectOutputStream(os);
		} catch (Exception e) {
			e.printStackTrace();
			closeSocket();
		}
	}

	@Override
	public void run() {
		isRun = true;
		try {
			while (isRun) {
				Request rq = (Request) ois.readObject();
				Controller controller = Controller.getInstance();
				controller.excute(rq, this);
			}
		} catch (Exception e) {
			for (String id : IMServer.map.keySet()) {
				if (IMServer.map.get(id) == this) {
					IMServer.map.remove(id);
				}
			}
		}
		closeSocket();
	}

	public void closeSocket() {
		try {
			is.close();
			ois.close();
			if (os == null) {
				os.close();
				oos.close();
			}
			socket.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	public boolean isRun() {
		return isRun;
	}

	public void setRun(boolean isRun) {
		this.isRun = isRun;
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		try {
			is.close();
			ois.close();
			if (os == null) {
				os.close();
				oos.close();
			}
			socket.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void send(Object object) {
		try {

			if (!socket.isClosed()) {
				System.out.println(object.toString());
				oos.writeObject(object);
			}
		} catch (Exception e) {
			for (String id : IMServer.map.keySet()) {
				if (IMServer.map.get(id) == this) {
					IMServer.map.remove(id);
				}
			}
			closeSocket();
		}
	}

}
